package com.cos.controller;

import com.cos.commons.R;
import com.cos.constant.CookieID;
import com.cos.constant.LoginSuccess;
import com.cos.feign.api.AddressFeign;
import com.cos.feign.api.OrderFeign;
import com.cos.service.OrdersService;
import com.cos.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private AddressFeign addressFeign;
    @Autowired
    private OrdersService ordersService;
    @GetMapping("/{page}.html")
    public String orderConfirm(@PathVariable String page, String gid, HttpSession session, ModelMap modelMap){
        Customer customer = (Customer) session.getAttribute(LoginSuccess.LOGIN_SUCCESS);
        List<String> list=new ArrayList<>();
        Map<String,Object> map=null;
        List<AddressEntity> addressEntityList=null;
        if (customer != null) {
            if (!StringUtils.isEmpty(gid)) {
                String[] split = gid.split(",");
                for (String s : split) {
                    list.add(s);
                }
                if (list.size()>0) {
                    addressEntityList = addressFeign.list(customer.getId());
                    map = orderFeign.getCarByUidAndPid(customer.getId(), list);
                }
            }else {
                addressEntityList=addressFeign.list(customer.getId());
                 map= orderFeign.getCarByUid(customer.getId());
            }

        }else {
            return "redirect:http://localhost/auth/login.html";
        }
        modelMap.put("addressList",addressEntityList);
        modelMap.put("map",map);
        return page;
    }


    @RequestMapping("/createOrder")
    public String createOrder(HttpSession httpSession, OrderParam orderParam) throws ExecutionException, InterruptedException {
        //判断用户是否登录
        String order=null;
        Customer customer = (Customer) httpSession.getAttribute(LoginSuccess.LOGIN_SUCCESS);
        if (customer != null) {
             order= ordersService.createOrder(orderParam, customer.getId());

        }else {
            return "redirect:http://localhost/auth/login.html";
        }

        return "redirect:http://localhost/pay/ali/pay?oid="+order;
    }

}
